<script lang="ts" setup>
  import { ref, watchEffect, computed, nextTick,defineProps } from "vue";
  import { message, Button } from 'ant-design-vue';
  import { useVbenVxeGrid } from '#/adapter/vxe-table';
  import { v4 as uuidv4 } from 'uuid';
  import { saveOrUpdate, getPageHeaders } from '#/api';
  import type { BatchConfig } from '../../utils/declar';

  // 存储字典数据
  const dictionaryListMap = ref(new Map());

  const props = defineProps({
    data: {
      type: Object as PropType<BatchConfig>,
      required: true,
    }
  });

  const gridEvents = {
    editClosed: ({ row }) => {
      dictionaryListMap.value.set(row.uuid, row);
    },
  };


  // **动态计算 Grid 配置**
  const gridOptions = ref({
    editConfig: {
      trigger: 'click',
      mode: 'cell'
    },
    columns: [],
    data: dictionaryListMap.value.values(),
    pagerConfig: {
      enabled: false,
    },
    sortConfig: {
      multiple: true,
    },
  });

  const [Grid, gridApi] = useVbenVxeGrid({ gridEvents, gridOptions });

  init();
  async function init() {
    if (props.data?.className) {
      const header = await getPageHeaders(props.data.className).then(res => res.columns);
      header.forEach(item=>{
        item.editRender = { name: 'CellInput' }
      });
      const headerData = [
        ...header,
        { field: 'action', fixed: 'right', slots: { default: 'action' }, title: '操作', width: 120 },
      ]
      headers.value = header;
      gridApi.setGridOptions({columns:headerData});
    }

    if (props.data?.tableData) {
      props.data.tableData.forEach(item => {
        const uuid = uuidv4();
        item.uuid = uuid;
        dictionaryListMap.value.set(uuid, item);
      });
      gridApi.setGridOptions({data:[...dictionaryListMap.value.values()]});
    }

  }

  // **获取表头数据**
  const headers = ref([]);


  // **添加一行**
  const addRow = async () => {
    const uuid = uuidv4();
    const addData = headers.value.reduce((obj, item) => {
      if(item.field==='sort'){
        obj[item.field] = dictionaryListMap.value.size + 1;
      } else {
        obj[item.field] = null;
      }
      return obj;
    }, {});
    const mergedObject = { ...addData, ...props.data.addToSubmit };
    const newData = {
      uuid,
      ...mergedObject
    };
    dictionaryListMap.value.set(uuid, newData);
    const data = Array.from(dictionaryListMap.value.values());
    gridApi.setGridOptions({ data });
  };

  // **删除一行**
  const removeRow = async (row) => {
    dictionaryListMap.value.delete(row.uuid);
    const data = Array.from(dictionaryListMap.value.values());
    gridApi.setGridOptions({ data });
  };

  // **提交数据**
  const submitData = async () => {
    if (dictionaryListMap.value.size === 0) {
      message.warn("至少要有一个数据字典！");
      return;
    }

    try {
      await saveOrUpdate({
        className: props.data.className,
        dataList: [...dictionaryListMap.value.values()],
      });
      message.success("字典提交成功！");
    } catch (error) {
      message.error("提交失败，请检查数据！");
      console.error(error);
    }
  };
</script>

<template>
  <div>
    <Grid>
      <template #action="{ row }">
        <Button type="link" @click="removeRow(row)">移除</Button>
      </template>
    </Grid>
    <div style="margin: 8px">
      <Button v-if="props.data.displayAddButton" type="dashed" block @click="addRow">+ 添加</Button>
      <Button type="primary" block @click="submitData" style="margin-top: 5px">提交</Button>
    </div>
  </div>
</template>
